02. Generics
Generics
Nd079 C1 L5 A02 Generics
Generics allow us to write methods that handle a whole group of different data types—in other words, to write methods that are generic.
The benefits of using Generics are:
- Stronger type checks at compile time.
- They remove the need to cast objects.
- They allow developers to implement generic algorithms.
Put another way, generics are a way to parameterize class types into classes, methods, and variables.
Syntax Example
Here is some code that creates a list of strings without using generics:
List strings = new List();
How do we know what’s in this list? The list is called strings
, but that is just the name we chose. We would need to cast the items in order to use them as String types.
With generics, we can identify what types are stored in the list. The syntax for a generic is very simple—it's just bracket with the type inside, < type >
. So in this example, we can add <String>
right next to List
to identify what types are stored in the list:
List<String> strings = new <String>ArrayList();
Because we've used generics to identify the items in the list as Strings, we could now call methods directly on them without having to first cast them.